<template>
  <div class="chat-input-box">
    <!-- 图片预览区域 -->
    <div v-if="uploadedImageForUnderstanding || imageConfig.uploadedImage" class="image-preview-section">
      <!-- 折叠控制栏 -->
      <div class="preview-control-bar">
        <div class="control-title">
          <el-icon class="title-icon"><Picture /></el-icon>
          <span>图片预览</span>
          <span class="image-count">({{ (uploadedImageForUnderstanding ? 1 : 0) + (imageConfig.uploadedImage ? 1 : 0) }})</span>
        </div>
        <el-button
          size="small"
          text
          @click="isImagePreviewCollapsed = !isImagePreviewCollapsed"
          class="collapse-btn"
        >
          <el-icon>
            <ArrowDown v-if="isImagePreviewCollapsed" />
            <ArrowUp v-else />
          </el-icon>
        </el-button>
      </div>

      <!-- 图片预览内容 -->
      <el-collapse-transition>
        <div v-if="!isImagePreviewCollapsed" class="preview-content">
          <!-- 图片理解预览 -->
          <div v-if="uploadedImageForUnderstanding" class="image-preview-card">
            <div class="preview-header">
              <div class="preview-title">
                <el-icon class="title-icon"><View /></el-icon>
                <span>图片理解</span>
              </div>
              <el-button
                size="small"
                text
                type="danger"
                @click="clearUploadedImageForUnderstanding"
                class="remove-btn"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
            <div class="preview-image">
              <img :src="uploadedImageForUnderstanding" alt="待理解的图片" />
            </div>
          </div>

          <!-- 图片生成预览 -->
          <div v-if="imageConfig.uploadedImage" class="image-preview-card">
            <div class="preview-header">
              <div class="preview-title">
                <el-icon class="title-icon"><Picture /></el-icon>
                <span>参考图片</span>
              </div>
              <el-button
                size="small"
                text
                type="danger"
                @click="clearUploadedImageForGeneration"
                class="remove-btn"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
            <div class="preview-image">
              <img :src="imageConfig.uploadedImage" alt="参考图片" />
            </div>
          </div>
        </div>
      </el-collapse-transition>
    </div>

    <!-- 主输入区域 -->
    <div class="main-input-container">
      <!-- 输入框 -->
      <div class="input-wrapper">
        <el-input
          v-model="inputValue"
          type="textarea"
          :placeholder="getPlaceholderText()"
          :disabled="disabled"
          :autosize="{ minRows: 1, maxRows: 6 }"
          resize="none"
          class="message-input"
          @keydown="handleKeydown"
          @input="handleInput"
          ref="inputRef"
        />

        <!-- 功能按钮组 -->
        <div class="action-buttons">
          <!-- 图片理解按钮 -->
          <el-tooltip content="上传图片进行AI理解分析" placement="top">
            <el-upload
              :show-file-list="false"
              :before-upload="handleImageUnderstandingUpload"
              accept="image/*"
              class="upload-btn"
            >
              <el-button
                size="small"
                :type="uploadedImageForUnderstanding ? 'primary' : 'default'"
                class="function-btn understand-btn"
              >
                <el-icon><View /></el-icon>
                <span class="btn-text">理解</span>
              </el-button>
            </el-upload>
          </el-tooltip>

          <!-- 图片生成按钮 -->
          <el-tooltip content="AI图片生成" placement="top">
            <el-button
              size="small"
              :type="aiMode === 'image_generation' ? 'primary' : 'default'"
              class="function-btn generate-btn"
              @click="toggleImageGeneration"
            >
              <el-icon><Picture /></el-icon>
              <span class="btn-text">生成</span>
            </el-button>
          </el-tooltip>

          <!-- 图片生成配置按钮 -->
          <el-tooltip v-if="aiMode === 'image_generation'" content="配置生成参数" placement="top">
            <el-button
              size="small"
              text
              type="info"
              class="function-btn"
              @click="showConfigPanel = !showConfigPanel"
            >
              <el-icon><Setting /></el-icon>
            </el-button>
          </el-tooltip>

          <!-- 发送按钮 -->
          <el-button
            v-if="!isStreaming"
            :disabled="!canSend"
            @click="handleSend"
            type="primary"
            size="small"
            class="send-button"
          >
            <el-icon><Promotion /></el-icon>
          </el-button>

          <!-- 停止按钮 -->
          <el-button
            v-else
            @click="handleStop"
            type="danger"
            size="small"
            class="send-button"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 配置面板 -->
      <el-collapse-transition>
        <div v-if="showConfigPanel && aiMode === 'image_generation'" class="config-panel">
          <div class="config-content">
            <!-- 图片生成配置 -->
            <div class="config-section">
              <div class="config-item">
                <label class="config-label">图片尺寸</label>
                <el-select v-model="imageConfig.imageSize" size="small" class="config-select">
                  <el-option
                    v-for="option in imageSizeOptions"
                    :key="option.value"
                    :label="`${option.label} (${option.ratio})`"
                    :value="option.value"
                  />
                </el-select>
              </div>

              <div class="config-item">
                <label class="config-label">生成数量</label>
                <el-select v-model="imageConfig.batchSize" size="small" class="config-select">
                  <el-option label="1张" :value="1" />
                  <el-option label="2张" :value="2" />
                  <el-option label="3张" :value="3" />
                  <el-option label="4张" :value="4" />
                </el-select>
              </div>

              <div class="config-item">
                <label class="config-label">引导强度</label>
                <el-slider
                  v-model="imageConfig.guidanceScale"
                  :min="1"
                  :max="20"
                  :step="0.5"
                  show-input
                  size="small"
                  class="config-slider"
                />
              </div>

              <!-- 参考图片上传 -->
              <div class="config-item">
                <label class="config-label">参考图片</label>
                <el-upload
                  :show-file-list="false"
                  :before-upload="handleImageUpload"
                  accept="image/*"
                  class="reference-upload"
                >
                  <el-button size="small" :icon="Upload" type="primary">
                    {{ imageConfig.uploadedImage ? '重新上传' : '选择图片' }}
                  </el-button>
                </el-upload>
              </div>
            </div>
          </div>
        </div>
      </el-collapse-transition>
    </div>

    <!-- 输入提示 -->
    <div class="input-tips" v-if="showTips">
      <span class="tip-text">
        {{
          aiMode === 'image_generation' ? '描述图片内容，按 Enter 生成' :
          aiMode === 'image_understanding' ? '描述你想了解的内容，按 Enter 理解' :
          '按 Enter 发送，Shift + Enter 换行，Ctrl + V 粘贴图片'
        }}
      </span>
      <span class="char-count" :class="{ 'over-limit': isOverLimit }">
        {{ inputValue.length }}/{{ maxLength }}
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Promotion, Close, Setting, Upload, View, Picture, ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { useAIChatStore } from '@/stores/aiChatStore'
import type { ImageGenerationConfig } from '@/types/aiChat'
import { IMAGE_SIZE_OPTIONS } from '@/types/aiChat'

interface Props {
  modelValue: string
  placeholder?: string
  disabled?: boolean
  maxLength?: number
  showImageControls?: boolean // 是否显示图片生成控制
}

interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'send'): void
  (e: 'sendImage', prompt: string, config: ImageGenerationConfig): void
  (e: 'sendImageUnderstanding', message: string, imageBase64: string): void
  (e: 'stop'): void
  (e: 'keydown', event: KeyboardEvent): void
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '输入您的问题...',
  disabled: false,
  maxLength: 10000,
  showImageControls: true
})

const emit = defineEmits<Emits>()
const aiChatStore = useAIChatStore()

// 响应式数据
const inputRef = ref()
const inputValue = ref(props.modelValue)

// ========== AI功能模式相关状态 ==========
/** AI功能模式：text(文本聊天) | image_generation(图片生成) | image_understanding(图片理解) */
const aiMode = ref<'text' | 'image_generation' | 'image_understanding'>('text')

/** 是否显示配置面板 */
const showConfigPanel = ref(false)

/** 是否折叠图片预览 */
const isImagePreviewCollapsed = ref(false)

/** 图片理解模式下上传的图片 */
const uploadedImageForUnderstanding = ref<string>('')

/** 可选的图片尺寸选项（从类型定义中导入） */
const imageSizeOptions = IMAGE_SIZE_OPTIONS

/** 图片生成配置参数 */
const imageConfig = ref<ImageGenerationConfig>({
  imageSize: '1024x1024',    // 图片尺寸，默认1:1正方形
  batchSize: 1,              // 生成数量，1-4张
  guidanceScale: 7.5,        // 引导强度，控制与提示词的匹配程度
  numInferenceSteps: 20      // 推理步数，影响图片质量和生成时间
})

// 计算属性
const canSend = computed(() => {
  if (props.disabled) return false

  // 文本聊天模式：需要有输入内容
  if (aiMode.value === 'text') {
    return inputValue.value.trim().length > 0 && inputValue.value.length <= props.maxLength
  }

  // 图片生成模式：需要有输入内容
  if (aiMode.value === 'image_generation') {
    return inputValue.value.trim().length > 0 && inputValue.value.length <= props.maxLength
  }

  // 图片理解模式：需要有输入内容和上传的图片
  if (aiMode.value === 'image_understanding') {
    return inputValue.value.trim().length > 0 &&
           inputValue.value.length <= props.maxLength &&
           uploadedImageForUnderstanding.value.length > 0
  }

  return false
})

// 计算属性

const isOverLimit = computed(() => {
  return inputValue.value.length > props.maxLength
})

const showTips = computed(() => {
  return inputValue.value.length > 0 || isOverLimit.value
})

const isStreaming = computed(() => {
  return aiChatStore.isStreaming
})

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  inputValue.value = newValue
})

// 监听输入值变化
watch(inputValue, (newValue) => {
  emit('update:modelValue', newValue)
})

// 方法
const handleInput = () => {
  // 输入处理逻辑
}

const handleKeydown = (event: KeyboardEvent) => {
  emit('keydown', event)

  // Enter发送，Shift+Enter换行
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    handleSend()
  }

  // Ctrl+V 粘贴图片
  if (event.ctrlKey && event.key === 'v') {
    // 让默认粘贴事件先执行，然后检查剪贴板
    setTimeout(() => {
      handlePasteImage()
    }, 10)
  }
}

const handleSend = () => {
  if (canSend.value) {
    if (aiMode.value === 'image_generation') {
      // 图片生成模式 - 验证配置
      const config = { ...imageConfig.value }

      // 确保配置有默认值
      if (!config.imageSize) config.imageSize = '1024x1024'
      if (!config.batchSize) config.batchSize = 1
      if (!config.guidanceScale) config.guidanceScale = 7.5
      if (!config.numInferenceSteps) config.numInferenceSteps = 20

      emit('sendImage', inputValue.value, config)
    } else if (aiMode.value === 'image_understanding') {
      // 图片理解模式
      emit('sendImageUnderstanding', inputValue.value, uploadedImageForUnderstanding.value)
    } else {
      // 普通聊天模式
      emit('send')
    }
  }
}

const handleStop = () => {
  emit('stop')
}

// ========== 图片生成相关方法 ==========



const handleImageUpload = (file: File) => {
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请上传图片文件')
    return false
  }

  // 检查文件大小（限制为5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }

  // 转换为base64
  const reader = new FileReader()
  reader.onload = (e) => {
    imageConfig.value.uploadedImage = e.target?.result as string
  }
  reader.readAsDataURL(file)

  return false // 阻止自动上传
}

/**
 * 处理粘贴图片
 */
const handlePasteImage = async () => {
  try {
    // 检查剪贴板API是否可用
    if (!navigator.clipboard || !navigator.clipboard.read) {
      console.warn('剪贴板API不可用')
      return
    }

    // 读取剪贴板内容
    const clipboardItems = await navigator.clipboard.read()

    for (const clipboardItem of clipboardItems) {
      // 查找图片类型
      const imageTypes = clipboardItem.types.filter(type => type.startsWith('image/'))

      if (imageTypes.length > 0) {
        const imageType = imageTypes[0]
        const blob = await clipboardItem.getType(imageType)

        // 检查文件大小（限制为10MB，与上传功能保持一致）
        if (blob.size > 10 * 1024 * 1024) {
          ElMessage.error('图片大小不能超过10MB')
          return
        }

        // 转换为base64
        const reader = new FileReader()
        reader.onload = (e) => {
          const base64 = e.target?.result as string

          // 自动切换到图片理解模式
          aiMode.value = 'image_understanding'
          uploadedImageForUnderstanding.value = base64

          // 显示成功提示
          ElMessage.success('图片粘贴成功！已切换到图片理解模式')

          // 聚焦输入框
          nextTick(() => {
            const textareaEl = inputRef.value?.textarea || inputRef.value?.input
            if (textareaEl) {
              textareaEl.focus()
            }
          })
        }
        reader.readAsDataURL(blob)

        return // 只处理第一张图片
      }
    }
  } catch (error) {
    console.error('粘贴图片失败:', error)
    // 不显示错误提示，因为可能是粘贴文本
  }
}



// ========== 图片理解相关方法 ==========
const handleImageUnderstandingUpload = (file: File) => {
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请上传图片文件')
    return false
  }

  // 检查文件大小（限制为10MB）
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过10MB')
    return false
  }

  // 转换为base64
  const reader = new FileReader()
  reader.onload = (e) => {
    uploadedImageForUnderstanding.value = e.target?.result as string
    // 自动切换到图片理解模式
    aiMode.value = 'image_understanding'
    ElMessage.success('图片上传成功，已切换到图片理解模式')
  }
  reader.onerror = () => {
    ElMessage.error('图片读取失败')
  }
  reader.readAsDataURL(file)

  return false // 阻止自动上传
}

const clearUploadedImageForUnderstanding = () => {
  uploadedImageForUnderstanding.value = ''
}

const clearUploadedImageForGeneration = () => {
  imageConfig.value.uploadedImage = undefined
}

/**
 * 获取输入框占位符文本
 */
const getPlaceholderText = () => {
  if (uploadedImageForUnderstanding.value) {
    return '描述你想了解的内容...'
  }
  if (aiMode.value === 'image_generation') {
    return '描述您想要生成的图片...'
  }
  return props.placeholder
}

/**
 * 切换图片生成模式
 */
const toggleImageGeneration = () => {
  if (aiMode.value === 'image_generation') {
    aiMode.value = 'text'
    showConfigPanel.value = false
  } else {
    aiMode.value = 'image_generation'
  }
}

const focus = () => {
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const clear = () => {
  inputValue.value = ''
}

// 暴露方法给父组件
defineExpose({
  focus,
  clear
})
</script>

<style lang="scss" scoped>
.chat-input-box {
  width: 100%;
  background: var(--el-bg-color);
  border-radius: 12px;
  border: 1px solid var(--el-border-color);
  overflow: hidden;
  transition: all 0.3s ease;

  &:hover {
    border-color: var(--el-border-color-hover);
  }

  &:focus-within {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 2px var(--el-color-primary-light-9);
  }
}

// 图片预览区域
.image-preview-section {
  border-bottom: 1px solid var(--el-border-color-light);
  background: var(--el-bg-color-page);

  .preview-control-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    background: var(--el-fill-color-lighter);
    border-bottom: 1px solid var(--el-border-color-light);

    .control-title {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 13px;
      font-weight: 500;
      color: var(--el-text-color-regular);

      .title-icon {
        color: var(--el-text-color-secondary);
        font-size: 14px;
      }

      .image-count {
        color: var(--el-text-color-secondary);
        font-size: 12px;
      }
    }

    .collapse-btn {
      padding: 4px;
      width: 24px;
      height: 24px;

      &:hover {
        background: var(--el-fill-color);
      }

      .el-icon {
        font-size: 14px;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .preview-content {
    padding: 8px 12px;
  }

  .image-preview-card {
    background: var(--el-bg-color);
    border-radius: 6px;
    overflow: hidden;
    box-shadow: var(--el-box-shadow-light);

    &:not(:last-child) {
      margin-bottom: 8px;
    }

    .preview-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 6px 10px;
      background: var(--el-fill-color-lighter);
      border-bottom: 1px solid var(--el-border-color-light);

      .preview-title {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
        font-weight: 500;
        color: var(--el-text-color-regular);

        .title-icon {
          color: var(--el-color-primary);
          font-size: 14px;
        }
      }

      .remove-btn {
        padding: 2px;
        width: 20px;
        height: 20px;

        &:hover {
          background: var(--el-color-danger-light-9);
        }

        .el-icon {
          font-size: 12px;
        }
      }
    }

    .preview-image {
      padding: 6px;

      img {
        width: 100%;
        max-height: 60px;
        object-fit: contain;
        border-radius: 4px;
      }
    }
  }
}

// 主输入区域
.main-input-container {
  padding: 8px;

  .input-wrapper {
    position: relative;
    display: flex;
    align-items: flex-end;
    gap: 8px;

    .message-input {
      flex: 1;

      :deep(.el-textarea__inner) {
        border: none;
        box-shadow: none;
        padding: 8px 12px;
        font-size: 14px;
        line-height: 1.5;
        resize: none;
        background: transparent;

        &:focus {
          box-shadow: none;
        }
      }
    }

    .action-buttons {
      display: flex;
      align-items: center;
      gap: 4px;
      flex-shrink: 0;

      .function-btn {
        height: 32px;
        padding: 0 8px;
        border-radius: 6px;
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
        gap: 4px;

        &:hover {
          background: var(--el-color-primary-light-9);
        }

        &.is-type-primary {
          background: var(--el-color-primary-light-9);
          color: var(--el-color-primary);
        }

        .btn-text {
          font-size: 12px;
          font-weight: 500;
        }
      }

      .generate-btn {
        background: #6366f1;
        color: white;
        border: none;
        font-weight: 500;

        &:hover {
          background: #5855eb;
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3);
        }

        &.is-type-primary {
          background: #409eff;

          &:hover {
            background: #3a8ee6;
          }
        }
      }

      .understand-btn {
        background: var(--el-fill-color-lighter);
        color: var(--el-text-color-regular);
        border: 1px solid var(--el-border-color);

        &:hover {
          background: var(--el-fill-color);
          border-color: var(--el-border-color-hover);
          transform: translateY(-1px);
          box-shadow: var(--el-box-shadow-light);
        }

        &.is-type-primary {
          background: #10b981;
          color: white;
          border: none;

          &:hover {
            background: #059669;
            box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
          }
        }
      }

      .upload-btn {
        .el-upload {
          .el-button {
            height: 32px;
            padding: 0 8px;
            border-radius: 6px;
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
      }

      .send-button {
        width: 36px;
        height: 36px;
        padding: 0;
        border-radius: 8px;
        font-weight: 500;
      }
    }
  }
}

// 配置面板
.config-panel {
  margin-top: 12px;
  padding: 16px;
  background: var(--el-fill-color-lighter);
  border-top: 1px solid var(--el-border-color-light);

  .config-content {
    .config-section {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;

      .config-item {
        display: flex;
        flex-direction: column;
        gap: 6px;

        .config-label {
          font-size: 13px;
          font-weight: 500;
          color: var(--el-text-color-regular);
        }

        .config-select {
          width: 100%;
        }

        .config-slider {
          width: 100%;
        }

        .reference-upload {
          .el-button {
            width: 100%;
          }
        }
      }
    }
  }
}

// 输入提示区域
.input-tips {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0px 16px;
  background: var(--el-fill-color-lighter);
  border-top: 1px solid var(--el-border-color-light);
  font-size: 12px;

  .tip-text {
    color: var(--el-text-color-secondary);
  }

  .char-count {
    color: var(--el-text-color-placeholder);
    font-weight: 500;

    &.over-limit {
      color: var(--el-color-danger);
    }
  }
}
</style>
